package com.cgnpc.cuddemo.funcInstance.application.impl;

import com.cgnpc.cud.core.ftp.IFtpClient;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.framework.utils.HttpServlet;
import com.cgnpc.cuddemo.funcInstance.application.ICudFileApplication;
import com.cgnpc.cuddemo.funcInstance.domain.CudFile;
import com.cgnpc.cuddemo.funcInstance.service.ICudFileService;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.utils.IOUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/******************************
 * 用途说明: cudfile应用层
 * 作者姓名: PXMWRYA
 * 创建时间: 2019/11/20 14:39
 ******************************/
@Component
//@Slf4j
public class CudFileApplictionImpl implements ICudFileApplication {
    //日志类
    private static final Logger log = LoggerFactory.getLogger(CudFileApplictionImpl.class);

    @Autowired
    ICudFileService cudFileService;

    @Autowired(required = false)
    IFtpClient ftpClient;

//    public static final String RESOURCE_PATH = "/src/main/resources/upfile/";
//    public static final String RESOURCE_PATH = "/webapps/upfile/";
    @Value("${upload.file.url:}")
    String resourcePath;

    /**********************************
    * 用途说明: 上传文件
    * 参数说明 file
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional
    public CudFile upfile(MultipartFile file) throws Exception {
        //对文件进行重命名 避免重复
        String fileRealName = file.getOriginalFilename();
        String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String fileName = IDHelper.uuid() + prefix;

        boolean flag = false;
        log.info("开始上传文件");
        InputStream inputStream =null;
        try{
            inputStream =file.getInputStream();
            flag = ftpClient.upload(file.getInputStream(),fileName);
        }catch (Exception e){

        }finally {
            IOUtil.close(inputStream);
        }

        log.info("flag:[{}]",flag);
        log.info("上传文件结束");
        //添加文件信息
        if(flag){

            CudFile cudFile =  addFile(fileRealName,fileName,"ftp");
            return cudFile;
        }else{
            return null;
        }
    }

    /**********************************
    * 用途说明: 添加一条文件信息
    * 参数说明 realName
    * 参数说明 name
    * 参数说明 url
    * 返回值说明:
    ***********************************/
    @Override
    public CudFile addFile(String realName,String name, String url) throws Exception {
        boolean flag = false;
        CudFile cudFile = new CudFile();
        cudFile.setFileId(IDHelper.uuid());
        cudFile.setCreateTime(new Date());
        cudFile.setFileName(name);
        cudFile.setFileRealName(realName);
        cudFile.setFileUrl(url);
        cudFile.setFileUploadPeople(CurrentUser.getUser());
        flag = cudFileService.save(cudFile);
        if(flag){
            return cudFile;
        }else{
            return null;
        }

    }

    /**********************************
    * 用途说明: 下载文件
    * 参数说明 map
    * 返回值说明:
    ***********************************/
    @Override
    public void downloadFile(Map map) {
        try{
            String fileRealName = map.get("fileRealName").toString();
            HttpServletResponse response = HttpServlet.getResponse();
            ByteArrayOutputStream outputStream = (ByteArrayOutputStream) ftpClient.download(map.get("fileName").toString());
            byte[] data = outputStream.toByteArray();
           // response.setHeader("Content-Disposition", "attachment; filename="+ new String(fileRealName.getBytes("utf-8"), "ISO8859-1"));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileRealName, "UTF-8"));
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }

//        String url = map.get("fileUrl").toString();
//        String fileRealName = map.get("fileRealName").toString();
//        BufferedInputStream bis = null;
//        BufferedOutputStream bos = null;
//        File file = new File(url);
//        HttpServletResponse response = HttpServlet.getResponse();
//
//        try{
//            if(file.exists()){
//                FileInputStream is = new FileInputStream(file);
//                bis = new BufferedInputStream(is);
//                response.setCharacterEncoding("UTF-8");
//
//                response.setContentType("application/octet-stream");
//                response.setHeader("Content-disposition", "attachment; filename="+ new String(fileRealName.getBytes("utf-8"), "ISO8859-1"));
//                bos = new BufferedOutputStream(response.getOutputStream());
//
//                //定义缓冲池大小，开始读写
//                byte[] buff = new byte[2048];
//                int bytesRead;
//                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//                    bos.write(buff, 0, bytesRead);
//                }
//                //刷新缓冲，写出
//                bos.flush();
//
//            }else{
//                throw new Exception("文件不存在相应地址,请检查");
//            }
//        }catch(Exception e){
//            e.printStackTrace();
//        }finally {
//            if(bis != null){
//                try {
//                    bis.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if(bos != null){
//                try {
//                    bos.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
    }

    /**********************************
    * 用途说明: 删除文件
    * 参数说明 map
    * 返回值说明:
    ***********************************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delFile(Map map) throws Exception {
        boolean flag = false;
        String fileId = map.get("fileId").toString();
        CudFile file = cudFileService.getById(fileId);
        String fileName = file.getFileName();
        flag = cudFileService.removeById(fileId);
        if(flag){
            if(ftpClient.delete(fileName)){
                return flag;
            }else{
                throw new Exception("删除文件失败");
            }
        }else{
            throw new Exception("删除文件数据失败");
        }
    }
}